/**
 * Created by LeungZ on 2016/10/17.
 */
import delTmp from './form/alert.html';
import delCtrl from './form/alert.ctrl.js';

class App {
    constructor(list, appSrv, ctgNotification, $uiModal,$rootScope) {
        "ngInject";
        this._appSrv = appSrv;
        this._notification = ctgNotification;
        this._uiModal = $uiModal;

        this.page = {
            currentPage: 1,
            totalItems: 0
        };
        this.filter = {
            name: null
        };

        if (list) {
            this.table = list.list;
            this.page.totalItems = list.total;
        } else this.table = [];
    }

    search() {
        this.page.currentPage = 1;
        this.getList();
    }

    getList() {
        this.table = null;
        this.getData();
    }

    getData(){
        this._appSrv.getAppList({currentPage: this.page.currentPage}, this.filter).then(data=> {
            this.table = data.list;
            this.page.totalItems = data.total;
        }).catch(()=> {
            if(!this.table){
                this.table = [];
                this.page.totalItems = 0;
            }
            this._notification.error('获取构建列表数据有误.');
        });
    }

    deleteApp(elem) {
        this._uiModal.open({
            templateUrl: delTmp,
            controller: delCtrl,
            controllerAs: 'vm',
            windowClass: 'alert-dialog alert-dialog-ctg',
            resolve: {
                alert: function () {
                    return {
                        appCode: elem.appCode,
                        action: '删除'
                    }
                }
            }
        }).result.then(()=> {
                elem.deleting = true;
                this._appSrv.deleteApp(elem.appId).then(data=> {
                    if (this.table.length == 1 && this.page.currentPage > 1)  this.page.currentPage--;

                    this.getData();
                    this._notification.success('删除应用 ' + elem.appCode + ' 成功.');
                }).catch(data=> {
                    this._notification.error('删除应用 ' + elem.appCode + ' 失败.');
                }).finally(()=> {
                    elem.deleting = false;
                })
            });
    }
}
export default App